<template>
  <div class="app-container">
    <el-form ref="form" :model="form" label-width="150px">
      <el-form-item label="活动标题">
        <el-col :span="20">
          <el-input v-model="form.title" disabled />
        </el-col>
      </el-form-item>
      <el-form-item label="活动banner">
        <el-col :span="20">
          <el-upload
            class="avatar-uploader"
            action
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            :on-change="getFile"
            :auto-upload="false"
            list-type="picture-card"
          >
            <div  class="upload-before-container">
              <div class="textbox">
                <span class="txt addicon">
                  <img src="../../assets/upload-icon.png" alt />
                </span>
                <span class="txt">建议上传尺寸</span>
                <span class="txt">1920*720</span>
                <span class="txt">(上传格式：jpg/png/svg)</span>
              </div>
            </div>
          </el-upload>
        </el-col>
      </el-form-item>
      <div>
        <h4>一审规则设置</h4>
      </div>
      <el-form-item label="活动评审起止时间">
        <el-col :span="3.5">
          <el-date-picker
          :clearable="false"
            v-model="form.level1.start_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled1"
            class="time-box"
            prefix-icon='el-icon-date'
          />
    
        </el-col>
        <span  class="line">- -</span>
        <el-col :span="3.5">
          <el-date-picker
            v-model="form.level1.end_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled1"
            class="time-box"
             prefix-icon='el-icon-date'
             :clearable="false"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="最少点评入围作品数">
        <el-col :span="2">
          <el-input v-model="form.level1.minimum" type="text" :disabled="disabled1" />
        </el-col>
      </el-form-item>
      <el-form-item label="最多点评入围作品数">
        <el-col :span="2">
          <el-input v-model="form.level1.maxmum" type="text" :disabled="disabled1" />
        </el-col>
      </el-form-item>
      <el-form-item label="作品数≥">
        <el-col :span="2">
          <el-input v-model="form.level1.votes" type="text" :disabled="disabled1" />
        </el-col>
        <el-col :span="12">
          <span class="tips">* 一审晋升规则，入围作品总票数需≥设置的票数，方可晋级下一评审阶段</span>
        </el-col>
      </el-form-item>
      <el-form-item label="活动评委">
        <el-col :span="20">
          <el-checkbox-group v-model="form.level1.teacherIds" :disabled="disabled1">
            <el-checkbox-button
              v-for="item in judgesOptions"
              :label="item.id"
              :key="item.id"
            >{{item.username}}</el-checkbox-button>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <div class="line-x"></div>
      <el-row class="title-box" :gutter="20">
        <el-col :span="2
        ">二级设置</el-col>
        <el-col :span="1">
          <el-switch
            v-model="form.level2.status"
            active-color="#00bfd6"
            inactive-color="#eaecf0"
            :active-value="1"
            :inactive-value="0"
            :disabled="disabled2"
          />
          
        </el-col>
        <span style="font-size:14px;color:#999;font-weight:400;">（ 按钮开启：禁用二级评审 ）</span>
      </el-row>
      <div>
        <h4>二审规则设置</h4>
      </div>
      <el-form-item label="评星数量设置">
        <el-col :span="2">
          <el-input v-model="form.level2.star_level" type="text" :disabled="disabled2" />
        </el-col>
      </el-form-item>
      <el-form-item label="活动评审起止时间">
        <el-col :span="3.5">
          <el-date-picker
            v-model="form.level2.start_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled2"
            class="time-box"
             prefix-icon='el-icon-date'
             :clearable="false"
          />
        </el-col>
        <span  class="line">- -</span>
        <el-col :span="3.5">
          <el-date-picker
            v-model="form.level2.end_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled2"
             class="time-box"
             prefix-icon='el-icon-date'
             :clearable="false"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="最少点评入围作品数">
        <el-col :span="2">
          <el-input v-model="form.level2.minimum" type="text" :disabled="disabled2" />
        </el-col>
      </el-form-item>
      <el-form-item label="总星数排名前">
        <el-col :span="2">
          <el-input v-model="form.level2.votes" type="text" :disabled="disabled2" />
        </el-col>
        <el-col :span="12">
          <span class="tips">* 以二审评审截止时间统计排名为准，晋升三审需总计排名靠前数</span>
        </el-col>
      </el-form-item>
      <el-form-item label="活动评委">
        <el-col :span="20">
          <el-checkbox-group v-model="form.level2.teacherIds" :disabled="disabled2">
            <el-checkbox-button
              v-for="item in judgesOptions"
              :label="item.id"
              value
              :key="item.id"
            >{{item.username}}</el-checkbox-button>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <div class="line-x"></div>
      <div>
        <h4>三审规则设置</h4>
      </div>
      <!-- <el-form-item label="最少点评入围作品数">
        <el-col :span="2">
          <el-input v-model="form.level3.minimum" type="text" :disabled="disabled3" />
        </el-col>
      </el-form-item> -->
      <el-form-item label="活动评审起止时间">
        <el-col :span="3.5">
          <el-date-picker
            v-model="form.level3.start_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled3"
            class="time-box"
             prefix-icon='el-icon-date'
             :clearable="false"
          />
        </el-col>
        <span  class="line">- -</span>
        <el-col :span="3.5">
          <el-date-picker
            v-model="form.level3.end_time"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
            :disabled="disabled3"
            class="time-box"
             prefix-icon='el-icon-date'
             :clearable="false"
          />
        </el-col>
      </el-form-item>
      <div v-for="(item, index) in dimensions" :key="index" style="padding-bottom:20px">
        <el-form-item label="维度标题">
          <el-col :span="20">
            <el-input
              v-model="item.title"
              @change="getChange(item.id)"
              placeholder="请输入维度标题"
              :disabled="disabled3"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="维度分值">
          <el-col :span="2">
            <el-input
              v-model.number="item.score"
              @change="getChange(item.id)"
              type="text"
              :disabled="disabled3"
            />
          </el-col>
          <el-col :span="1.8">
            <span style="color:red;margin-left:10px" v-if="isErr">请重新输入</span>
          </el-col>
        </el-form-item>
        <el-form-item label="维度文案">
          <el-col :span="20">
            <el-input
              v-model="item.content"
              :autosize="{ minRows: 4, }"
              show-word-limit
              type="textarea"
              placeholder="请输入维度文案"
              class="text-input"
              @change="getChange(item.id)"
              :disabled="disabled3"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="1">
              <el-button @click="addDimension(index)" :disabled="disabled3" class="addbtn">增加+</el-button>
            </el-col>
            <el-col :span="1" v-if="dimensions.length> 1">
              <el-button @click="removeDimension(index,item.id)" :disabled="disabled3" class="delbtn">删除-</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </div>
      <!-- <el-form-item  >
          <el-row :gutter="20">
            <el-col :span="1.5">
              <el-button @click="addDimension" class="addbtn">增加+</el-button>
            </el-col>
            <el-col :span="1.5" v-if="dimensions.length> 1">
              <el-button @click="removeDimension (index,item.id)" class="delbtn">删除-</el-button>
            </el-col>
          </el-row>
      </el-form-item>-->

      <el-form-item label="活动评委">
        <el-col :span="20">
          <el-checkbox-group v-model="form.level3.teacherIds" :disabled="disabled3">
            <el-checkbox-button
              v-for="item in judgesOptions"
              :label="item.id"
              :key="item.id"
            >{{item.username}}</el-checkbox-button>
          </el-checkbox-group>
        </el-col>
      </el-form-item>
      <el-form-item style="margin-top:40px">
        <el-button
          style="background:#00BFD6 ;color:#fff;width:120px"
          @click="onSubmit"
          :disabled="disabled3"
        >保存</el-button>
         <el-button
          style="width:120px"
          @click="$router.go(-1)"
        
        >返回</el-button>
      </el-form-item>
    </el-form>
     <el-dialog :visible.sync="dialogVisible" append-to-body>
    <img width="100%" :src="dialogImageUrl" alt />
  </el-dialog>
  </div>
</template>

<script>
import { getTeachersList } from "@/api/activity";
import { uploadActivityBanner } from "@/api/banner";
import { activityEdit, activityAdd, getActivityDetail } from "@/api/activity";
export default {
  data() {
    return {
      activity_id: "",
      fileList: [],
      title: "",
      form: {
        info: {
          banner: "",
          id: null
        },
        title: "",
        level1: {
          id: null,
          start_time: "", //开始时间
          end_time: "", //结束时间
          minimum: null, //最少入选
          maximum: null, //最多入选
          votes: null, //入选票数
          teacherIds: []
        },
        level2: {
          id: null,
          star_level: null,
          start_time: "",
          end_time: "",
          status: null, //二级审核开关
          minimum: null,
          votes: null,
          teacherIds: []
        },
        level3: {
          id: null,
          start_time: "",
          end_time: "",
          // minimum: null,
          teacherIds: [],
          dimension: []
        },
        dimension_edit: [],
        dimension_del: [],
        dimension_add: []
      },
      dimensions: [
        {
          sort_order: 1,
          title: "",
          score: "",
          content: ""
        }
      ],
      judgesOptions: [], //评委列表
      currentTime: new Date(), // 当前时间
      isErr: false,
      disabled1: false,
      disabled2: false,
      disabled3: false,
       dialogImageUrl:'',
       dialogVisible: false,
    };
  },

  created() {
    this.getAccountList();
    // 从路由查询参数中获取 activity_id
    this.activity_id = this.$route.params.id;
    // 如果 activity_id 需要作为数字使用，进行类型转换
    if (this.activity_id && !isNaN(this.activity_id)) {
      this.activity_id = parseInt(this.activity_id);
      this.getDetail();
    }
  },
  watch: {
    dimensions: {
      handler(newVal) {
        this.updateDimensionAdd(newVal);
      },
      deep: true
    }
  },
  computed: {
    totalScore() {
      return this.dimensions.reduce(
        (acc, dimension) => acc + dimension.score,
        0
      );
    }
  },
  methods: {
    // 时间判断
    getTimeSort(start, end) {
      const date1 = new Date(start);
      const date2 = new Date(end);
      const isBetweenDates = this.currentTime >= date1;
      return isBetweenDates;
    },
    getDetail() {
      let params = {};
      params.activity_id = this.activity_id;
      getActivityDetail(params).then(res => {
        // this.form = Object.assign({}, res.activity);
        this.form.info.id = res.activity.activity_id;
        if (res.activity.banner) {
          this.form.info.banner = res.activity.banner;
          this.fileList = [
            { name, url: process.env.VUE_APP_BASE_API + res.activity.banner }
          ];
        }

        this.form.title = res.activity.title;
        this.form.level1 = res.activity.level[0];

        this.form.level1.teacherIds = this.filterTeachersByIDs(
          this.judgesOptions,
          this.form.level1.teacherIds
        );
        this.form.level2 = res.activity.level[1];
        this.form.level2.teacherIds = this.filterTeachersByIDs(
          this.judgesOptions,
          this.form.level2.teacherIds
        );
        this.form.level3 = res.activity.level[2];
        this.form.level3.teacherIds = this.filterTeachersByIDs(
          this.judgesOptions,
          this.form.level3.teacherIds
        );
        if (
          this.form.level3.dimension &&
          this.form.level3.dimension.length > 0
        ) {
          this.dimensions = this.form.level3.dimension;
        }
        // 条件禁用
        // if (
        //   this.getTimeSort(
        //     this.form.level1.start_time,
        //     this.form.level1.end_time
        //   )
        // ) {
        //   this.disabled1 = !this.disabled1;
        // }
        // if (
        //   this.getTimeSort(
        //     this.form.level2.start_time,
        //     this.form.level2.end_time
        //   )
        // ) {
        //   this.disabled2 = !this.disabled2;
        // }
        // if (
        //   this.getTimeSort(
        //     this.form.level3.start_time,
        //     this.form.level3.end_time
        //   )
        // ) {
        //   this.disabled3 = !this.disabled3;
        // }
      });
    },
    updateSortOrders() {
      // 重新分配 sort_order
      this.dimensions.forEach((dimension, index) => {
        dimension.sort_order = index + 1;
      });
      this.form.dimension_edit = this.dimensions;
    },
    updateDimensionAdd(newVal) {
      this.form.dimension_add = newVal.filter(item => {
        return !item.id || item.id === null;
      });
    },
    getChange(id) {
      if (id) {
        // 获取当前改变的值
        const value = this.dimensions.find(item => item.id === id);

        // 避免重复的键值对
        const existingIndex = this.form.dimension_edit.findIndex(
          existing => existing.id === id
        );
        if (existingIndex === -1) {
          this.form.dimension_edit.push(value);
        } else {
          // 如果已有相同 id 的项，则更新该项
          this.form.dimension_edit[existingIndex] = value;
        }
      }
    },
    // 过滤 list 数组，只保留那些 id 包含在 teacherIds 数组中的教师信息
    filterTeachersByIDs(list, ids) {
      return list.filter(item => ids.includes(item.id)).map(item => item.id);
    },
    getAccountList() {
      getTeachersList()
        .then(res => {
          this.judgesOptions = res.list;
        })
        .catch(err => {});
    },
    removeDimension(index, id) {
      if (id) {
        this.form.dimension_del.push(id);
        this.dimensions.splice(index, 1);
        this.form.dimension_edit = this.form.dimension_edit.filter(
          item => item.id !== id
        );
      } else {
        this.dimensions.splice(index, 1);
      }
      this.updateSortOrders();
    },
    addDimension(index) {
      const newDimension = {
        sort_order: index + 1,
        title: "",
        score: "",
        content: ""
      };
      this.dimensions.splice(index + 1, 0, newDimension);
      // 重新计算所有维度的 sort_order
      this.updateSortOrders();
    },
    onSubmit() {
      if (this.totalScore > 100) {
        this.isErr = true;
        alert("维度分值不能超过100");
        return false;
      } else {
        this.isErr = false;
      }

      let params = Object.assign({}, this.form);
      params.level1_teachers = this.form.level1.teacherIds;
      params.level2_teachers = this.form.level2.teacherIds;
      params.level3_teachers = this.form.level3.teacherIds;
      this.form.dimension_edit = this.dimensions;
      // console.log(params);
      activityEdit(params).then(res => {
        this.$message.success(res.msg);
        this.$router.go(-1);
      });
    },
    getFile(file) {
      if (this.beforeUpload(file.raw)) {
        const formData = new FormData();
        formData.append("file", file.raw);

        uploadActivityBanner(formData)
          .then(result => {
            this.form.info.banner = result.banner;
          })
          .catch(error => {
            console.error("上传失败", error);
            this.$message.error("上传失败，请检查网络连接或文件格式大小！");
          });
      }
    },
    beforeUpload(file) {
      const allowedTypes = ["image/jpeg", "image/jpg", "image/png"];
      const isValidType = allowedTypes.includes(file.type);
      const isLt10M = file.size / 1024 / 1024 < 10; // 确保文件大小不超过10MB

      if (!isValidType) {
        this.$message.warning("上传图片只能是 jpeg、jpg、png 格式!");
      }
      if (!isLt10M) {
        this.$message.warning("上传图片大小不能超过 10MB!");
      }
      return isValidType && isLt10M;
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
      this.fileList = fileList;
      this.form.info.banner = null;
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url || file.response || file.raw;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多只能上传一张图片");
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 40px 40px 60px;
  min-width: 1400px;
  overflow-x: auto;
}
.line {
float: left;
width: 40px !important;
min-width: 40x !important;
  text-align: center;
 padding: 0 5px;
}
.line-x {
  margin: 50px 0;
  width: 100%;
  height: 1px;
  background: #e6e6e6;
}
.title-box {
  font-weight: bold;
  font-size: 18px;
  color: #000000;
  line-height: 29px;
}
.tips {
  margin-left: 20px;
  font-size: 14px;
  color: #999999;
  line-height: 29px;
}
h4 {
  margin: 30px 0;
  font-size: 16px;
  color: #4d4d4d;
  line-height: 29px;
}
/* ::v-deep .el-checkbox-button, */
::v-deep .el-checkbox-button__inner {
  padding: 10px 20px;
  margin: 0 5px;
  border-radius:20px !important;
  border: 1px solid #e6e6e6 !important;
  cursor: pointer;
  box-shadow: none;
}

::v-deep .el-checkbox-button__inner.is-checked {
}
::v-deep .el-checkbox-button.is-checked .el-checkbox-button__inner {
  border-color: none !important;
  color: #fff;
  background: #ff9e6e;
  box-shadow: none;
}

::v-deep .el-checkbox-button__inner:hover {
  color: #fff;
  background: #ff9e6e;
}
.addbtn {
  padding: 9px 16px;
  color: #fff;
  background: #00bfd6;
  border-radius: 6px;
}
.delbtn {
  padding: 9px 16px;
  color: #fff;
  background: #f56c6c;
  border-radius: 6px;
}
::v-deep .el-col {
  min-width: 100px;
}
.text-input ::v-deep .el-textarea__inner {
  background: #f5f5f5;
  border-radius: 6px;
  border: 1px solid #e6e6e6;
}
.upload-before-container {
  width: 300px;
  height: 240px;
  position: relative;
  .textbox {
    position: absolute;
    width: 80%;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .addicon {
    margin: 12px auto;
    width: 50px;
    height: 50px;
  }
  .txt {
    display: block;
    font-size: 14px;
    color: #666666;
    line-height: 21px;
  }
}
::v-deep .el-upload-list--picture-card .el-upload-list__item,
::v-deep .el-upload {
  width: 300px;
  height: 240px;
  background: #f5f5f5;
  border-radius: 6px;
  border: 1px solid #e6e6e6;
}
.time-box {

  min-width: 200px !important;
}
::v-deep .el-input__prefix{
left: unset;
right: 5px;
}
::v-deep  .el-input--prefix .el-input__inner{
padding-left: 10px;
}
::v-deep .el-switch__core{
width: 60px !important;
height: 28px !important;
    border-radius: 14px !important;
}
::v-deep .el-switch__core:after{
width: 24px;
height: 24px;
top: 50%;
transform: translateY(-50%);

}
::v-deep  .el-switch.is-checked .el-switch__core::after{
margin-left: -24px;
}
</style>